<template>
	<div>
		<div class="container">
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="current=1;loading=true;initData()">
					<!-- <a-row :gutter="20">
						<a-col :span="24">
							<a-form-item label="选择类型" name="ys_type">
								<a-radio-group v-model:value="searchState.ys_type" @change="current=1;loading=true;initData()">
									<a-radio-button v-for="option of yslist" :key="option.value" :value="option.value">{{ option.label }}</a-radio-button>
								</a-radio-group>
							</a-form-item>
						</a-col>
					</a-row>-->
					<a-row :gutter="20">
						<a-col :span="8">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear @change="changeSearchProjectId"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择类型">
								<a-select v-model:value="searchState.ys_type" :show-search="true" placeholder="请选择类型" :options="yslist" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择供应商" name="supplier_id">
								<a-select v-model:value="searchState.supplier_id" :show-search="true" placeholder="请选择" :options="filterUserList" option-filter-prop="label" allow-clear @change="changeSearchSupplierId"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="合同" name="ys_type">
								<a-select v-model:value="searchState.contract_id" :show-search="true" placeholder="请选择合同" :options="contractList" option-filter-prop="label" allow-clear @change="changeSearchContractId"></a-select>
							</a-form-item>
						</a-col>
						<!--						<a-col style="padding: 10px 0;" :span="8">-->
						<!--							<a-form-item label="结算类型" name="ys_type">-->
						<!--								<a-select v-model:value="searchState.ys_type" :show-search="true" placeholder="请选择" :options="yslist" option-filter-prop="label" allow-clear></a-select>-->
						<!--							</a-form-item>-->
						<!--						</a-col>-->
						<a-col :span="6">
							<a-form-item label="选择时间段">
								<a-range-picker v-model:value="searchState.date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
							</a-form-item>
						</a-col>
						<a-col :span="2">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
        v-if="!loading"使得:default-expand-all-rows="true"生效
				-->
				<a-table v-if="!loading" :row-selection="rowSelection" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="settlementSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'workflow_status'">
							<div>
								<a-workflow type="status" module="contract" :status="record.workflow_status" />
							</div>
						</template>
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="80" type="link" @click="showInfo(record)">
									<right-outlined />查看
								</a-button>
							</a-space>
						</template>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";

const { proxy } = getCurrentInstance();
import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, RightOutlined } from "@ant-design/icons-vue";

import { post, postJson } from "../utils";

import { usePagination } from "vue-request";
import { AWorkflow } from "@/components/index.js";

const projectOptions = ref([]);
const companyOptions = ref([]);
const userList = ref([]);
const filterUserList = ref([]);
const contractList = ref([]);
const route = useRoute();
const router = useRouter();
const query = route.query;
const searchRef = ref();
const selectRows = ref([]);
const searchState = reactive({
	ys_status: 2,
	supply_order_ids: [],
	ys_type: null
});
const yslist = [
	{ value: null, label: "全部" },
	{ value: 1, label: "钢筋" },
	{ value: 2, label: "混凝土" },
	{ value: 3, label: "周转材料" },
	{ value: 4, label: "机械" },
	{ value: 5, label: "其它" },
	{ value: 6, label: "辅助材料" },
	{ value: 7, label: "点工" }
];
const settleStatelist = [
	{ value: 1, label: "结算中" },
	{ value: 2, label: "已结算" },
	{ value: 3, label: "未知" }
];
const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		width: 130,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return text?.name;
		}
	},
	{
		title: "供应商名称",
		dataIndex: "supplier",
		sorter: false,
		width: 130,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text?.company_name || "";
		}
	},
	{
		title: "结算单名称",
		dataIndex: "name",
		sorter: false,
		width: 130,
		ellipsis: true,
	},
	{
		title: "结算单编码",
		dataIndex: "code",
		sorter: false,
		width: 130,
		ellipsis: true,
	},
	{
		title: "结算类型",
		dataIndex: "ys_type",
		sorter: false,
		width: 130,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return yslist.filter(item => item.value === parseInt(text))[0]?.label;
		}
	},
	{
		title: "申请时间",
		dataIndex: "settle_date",
		sorter: false,
		width: 130,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text ? dayjs(text).format("YYYY-MM-DD HH:mm:ss") : "";
		}
	},
	{
		title: "申请人",
		dataIndex: "opr",
		sorter: false,
		width: 130,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.fullname;
		}
	},
	{
		title: "状态",
		dataIndex: "workflow_status",
		width: 130,
		ellipsis: true,
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 300,
		align: "center"
	}
];
const rowSelection = ref({
	onChange: (ids, rows) => {
		selectRows.value = rows;
	}
});
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(",").map(item => parseInt(item))
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24])
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter(item => {
			return item.parseIds.includes(searchState.company_id);
		});
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
});
async function changeSearchProjectId() {
	searchState.supplier_id = null;
	searchState.contract_id = null;
	searchState.supply_order_ids = [];
	if (!searchState.project_id) {
		filterUserList.value = [];
		contractList.value = [];
		return;
	}
	post("supplyOrder/list", { project_id: searchState.project_id, ys_status: searchState.ys_status }).then(data => {
		const supplierIds = data.map(d => d.supplier_id);
		filterUserList.value = userList.value.filter(d => {
			return supplierIds.includes(d.value);
		});
	});
}
async function changeSearchSupplierId() {
	searchState.contract_id = null;
	searchState.supply_order_ids = [];
	post("contract/all", { project_id: searchState.project_id, supplier_id: searchState.supplier_id }).then(data => {
		contractList.value = data.map(item => {
			return {
				value: item.id,
				label: item.name
			};
		});
	});
}
function changeSearchContractId() {
	post("supplyOrder/materials", { contract_ids: JSON.stringify([searchState.contract_id]) }).then(data => {
		searchState.supply_order_ids = data.map(item => item.supply_order_id);
	});
}
post("user", { is_supplier: 1, page_size: 1000 }).then(({ data }) => {
	userList.value = data.map(d => {
		return {
			value: d.id,
			label: d.company_name || d.mobile
		};
	});
});
const { data, loading, run, current, pageSize, total } = usePagination(
	params => {
		const [start_date, end_date] = searchState.date_range || [];
		const search = {};
		if (searchState.company_id) {
			search.project_ids = projectOptions.value
				.filter(item => {
					return item.parseIds.includes(searchState.company_id);
				})
				.map(item => item.value)
				.join(",");
			if (!search.project_ids) {
				return [];
			}
		}
		return postJson("settlement/audited/list", { ...params, ...searchState, ...search, start_date, end_date });
	},
	{
		defaultParams: [
			{
				page_size: 10
			}
		],
		pagination: {
			currentKey: "page",
			pageSizeKey: "page_size",
			totalKey: "total"
		}
	}
);

const settlementSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value,
	showTotal() {
		return `共 ${total.value} 条`;
	},
	showSizeChanger: true
}));

const initData = (pag, filters, sorter) => {
	selectRows.value = [];
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = {
		...filters,
		...searchState
	};
	const query = {};
	if (pag?.pageSize) {
		query["page_size"] = pag?.pageSize;
	}
	if (pag?.current) {
		query["page"] = pag?.current;
	}
	for (const key in filters) {
		if (key === "date_range") {
			const one = filters.date_range;
			if (one?.length) {
				query["start_date"] = one[0];
				query["end_date"] = one[1];
			}
		} else {
			query[key] = filters[key];
		}
	}

	router.replace({
		query: {
			...query
		}
	});
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.ys_type) searchState.ys_type = parseInt(query.ys_type);
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.supplier_id) searchState.supplier_id = parseInt(query.supplier_id);
	if (query.contract_id) searchState.contract_id = parseInt(query.contract_id);
	if (query.code) searchState.code = query.code;
	if (query.start_date && query.end_date) searchState.date_range = [query.start_date, query.end_date];
	const pag = {};
	if (query.page) {
		pag["current"] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag["pageSize"] = parseInt(query.page_size);
	}
	initData(pag);
}
const showInfo = record => {
	router.push(`/settlement/manage/info?id=${record.id}&from=/settlement/history`);
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
